package com.ruoyi.system.service.impl;

import cn.hutool.core.lang.Assert;
import com.ruoyi.common.core.constant.ClientConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteTeachService;
import com.ruoyi.system.api.domain.Student;
import com.ruoyi.system.bo.TurnOverClientBo;
import com.ruoyi.system.domain.Prospects;
import com.ruoyi.system.domain.Teacher;
import com.ruoyi.system.domain.TurnOverLog;
import com.ruoyi.system.mapper.ProspectsMapper;
import com.ruoyi.system.mapper.TeacherMapper;
import com.ruoyi.system.mapper.TurnOverLogMapper;
import com.ruoyi.system.query.ProspectsQuery;
import com.ruoyi.system.service.IProspectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 潜在客户Service业务层处理
 * 
 * @author tong
 * @date 2024-01-22
 */
@Service
public class ProspectsServiceImpl implements IProspectsService 
{
    @Autowired
    private ProspectsMapper prospectsMapper;


    @Autowired
    private RedisService redisService;

    @Autowired
    private TurnOverLogMapper turnOverLogMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private RemoteTeachService remoteTeachService;

    /**
     * 查询潜在客户
     * 
     * @param id 潜在客户主键
     * @return 潜在客户
     */
    @Override
    public Prospects selectProspectsById(Long id)
    {
        return prospectsMapper.selectProspectsById(id);
    }

    /**
     * 查询潜在客户列表
     * 
     * @param prospects 潜在客户
     * @return 潜在客户
     */
    @Override
    @Transactional
    public List<Prospects> selectProspectsList(Prospects prospects)
    {
        // 获取当前登录用户的ID 以用户的ID作为查询条件，每一个用户只能查询自己的潜在客户
        prospects.setEntrantTeacher(SecurityUtils.getUserId().toString());
        return prospectsMapper.selectProspectsList(prospects);
    }

    /**
     * 新增潜在客户
     * 
     * @param prospects 潜在客户
     * @return 结果
     */
    @Override
    public int insertProspects(Prospects prospects)
    {


        //校验---判断该潜在客户是否存在 通过手机号校验
        Prospects selectProspectsByQuery = prospectsMapper.selectProspectsByQuery(new ProspectsQuery().setPhone(prospects.getPhone()));
        Assert.isTrue(selectProspectsByQuery == null,"该客户已经添加过，请勿重复添加！");

        //新增时 使用轮询算法 将潜在学员分配给老师进行咨询
        //1.查询教师列表
        //todo 测试数据  待改
//        teacherMapper.selectTeacherList()
        ArrayList<Teacher> teachers = new ArrayList<>();
        Teacher teacher1 = new Teacher();
        teacher1.setId(1L);
        teacher1.setName("张三");

        Teacher teacher2 = new Teacher();
        teacher2.setId(2L);
        teacher2.setName("李四");

        teachers.add(teacher1);
        teachers.add(teacher2);


        String key  = "Assign_Counters";

        //如果缓存中的分配计数器是null 就缓存一个计数器
        Object cacheObject = redisService.getCacheObject(key);
        if (cacheObject == null || cacheObject.equals("")){
            int value = 0;
            redisService.setCacheObject(key,value,24L, TimeUnit.HOURS);
        }
        Integer assignCounters = (Integer) cacheObject;

        //2.分配
        Teacher teacher = teachers.get(assignCounters % teachers.size());
        prospects.setConsultTeacher(teacher.getName());

        //3.计数器自增
        redisService.setCacheObject(key,++assignCounters);

        //4.设置主键为雪花ID

//        //构建雪花ID生成器
//        long workerId = 1;
//        long datacenterId = 1;
//        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
//
//        //生成雪花ID
//        prospects.setId(snowflake.nextId());
        return prospectsMapper.insertProspects(prospects);
    }

    /**
     * 修改潜在客户
     * 
     * @param prospects 潜在客户
     * @return 结果
     */
    @Override
    public int updateProspects(Prospects prospects)
    {
        return prospectsMapper.updateProspects(prospects);
    }

    /**
     * 批量删除潜在客户
     * 
     * @param ids 需要删除的潜在客户主键
     * @return 结果
     */
    @Override
    public int deleteProspectsByIds(Long[] ids)
    {
        return prospectsMapper.deleteProspectsByIds(ids);
    }

    /**
     * 删除潜在客户信息
     * 
     * @param id 潜在客户主键
     * @return 结果
     */
    @Override
    public int deleteProspectsById(Long id)
    {
        return prospectsMapper.deleteProspectsById(id);
    }

    /**
     * 移交客户
     *
     * @param turnOverClientBo
     */
    @Override
    @Transactional
    public void turnOver(TurnOverClientBo turnOverClientBo) {

        //1.查询潜在客户
        Prospects prospects = prospectsMapper.selectProspectsById(turnOverClientBo.getId());
        Assert.isTrue(prospects != null,"此客户不存在！");

        //2.修改客户的咨询教师
        String receiver = turnOverClientBo.getReceiver();
        prospects.setConsultTeacher(receiver);
        prospectsMapper.updateProspects(prospects);

        //3.保存移交记录表
        TurnOverLog turnOverLog = new TurnOverLog();
        turnOverLog.setTurnOverTime(new Date());
        turnOverLog.setReceiver(receiver);
        
        //4.设置移交人
        Long userId = SecurityUtils.getUserId();
        // todo teacher表的ID 要与若依的用户关联起来
        Teacher teacher = teacherMapper.selectTeacherById(userId);
        turnOverLog.setTrunOverPerson(teacher.getName());

        //5.被移交人
        turnOverLog.setTransferee(prospects.getName());

        turnOverLogMapper.insertTurnOverLog(turnOverLog);



    }

    /**
     * 转为正式学员
     * @param id
     */
    @Override

    public void toFullTrainees(Long id) {
        //业务校验

        //1. 判断客户是否存在
        Prospects prospects = prospectsMapper.selectProspectsById(id);
        Assert.isTrue(prospects != null,"该客户不存在");

        //2. 判断学员状态是否是有意向或者 无意向
        Assert.isTrue(prospects.getStatus() != ClientConstants.ClientStatus.HAVE_SIGNED_UP);
        //业务实现

        //2. 删除潜在客户 该客户已经是正式学员
        prospectsMapper.deleteProspectsById(prospects.getId());

        //3. 添加到学员表
        Student student = new Student();
        student.setStudentName(prospects.getName());
        student.setStudentAge(prospects.getAge());
        student.setStudentSex(prospects.getSex());
        student.setStudentPhone(prospects.getPhone());
        student.setCreateBy(SecurityUtils.getUserId().toString());
        student.setCreateTime(new Date());
        student.setRemark("潜在客户转为正式学员");
        R r = remoteTeachService.remoteInsert(student);
        Assert.isTrue(r.getCode() == 200,"远程调用异常");
    }
}
